<template>
	<div class="manage-detail">
		<el-row :gutter="50">
			<el-col :span="12" v-loading="loading">
				<el-form ref="ruleFormRef" :model="detailItem" :rules="rules" label-width="110px" class="demo-ruleForm">
					<el-row :gutter="20" justify="center" align="middle">
						<el-col :span="4">
							<div class="manage-pic">
								<span v-if="detailItem.icon"><img width="70" :src="detailItem.icon" alt="" /></span>
								<span v-else>{{ (detailItem.name + '').substr(0, 1) }}</span>
							</div>
						</el-col>
						<el-col :span="10">
							<el-form-item label="名字" prop="name">
								<el-input maxlength="200" v-model="detailItem.name" placeholder="请输名字" />
							</el-form-item>
						</el-col>
						<el-col :span="10">
							<el-form-item label="姓氏" prop="surname">
								<el-input maxlength="200" v-model="detailItem.surname" placeholder="请输姓氏" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="电子邮件" prop="email">
						<el-input show-word-limit maxlength="200" v-model="detailItem.email" placeholder="请输入电子邮件" />
					</el-form-item>
					<el-row>
						<el-col :span="12">
							<el-form-item label="username" prop="username" style="margin-bottom: 10px !important">
								<el-input disabled maxlength="200" v-model="detailItem.username" placeholder="请输入username" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="businessname" prop="username">
								<el-input maxlength="200" v-model="detailItem.businessname" placeholder="请输入username" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="客户全名" prop="allname">
								<el-input disabled maxlength="200" v-model="detailItem.allname" placeholder="请输入全名" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="ssn" prop="ssn">
								<el-input maxlength="200" v-model="detailItem.ssn" placeholder="请输入全名" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="电话号码" prop="phoneNumber">
						<el-form inline :model="phoneList" label-width="120px">
							<el-form-item
								v-for="(item, index) in phoneList"
								:key="index"
								:label="item.name"
								:prop="item.number"
								style="margin-bottom: 10px; width: 100%"
							>
								<el-input show-word-limit maxlength="200" v-model="item.number" placeholder="请输入电话号码" style="width: 100%" />
							</el-form-item>
						</el-form>
					</el-form-item>
					<el-row>
						<el-col :span="12">
							<el-form-item label="生日" prop="birthday">
								<el-date-picker disabled v-model="detailItem.birthday" value-format="YYYY-MM-DD" type="date" placeholder="生日" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="注册时间" prop="registrationTime">
								<el-input disabled readonly show-word-limit maxlength="200" :value="detailItem.registrationTime" placeholder="注册时间" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="是否订阅" prop="isSubscribe">
						<el-input
							disabled
							readonly
							show-word-limit
							maxlength="200"
							:value="detailItem.isSubscribe === 1 ? '已订阅' : '未订阅'"
							placeholder="是否订阅"
						/>
					</el-form-item>
					<el-form-item label="客户标签" prop="label">
						<el-select
							style="width: 100%"
							v-model="detailItem.label"
							multiple
							filterable
							:allow-create="false"
							default-first-option
							placeholder="选择客户标签"
						>
							<el-option v-for="item in labelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
				<el-row>
					<div class="manage-btns">
						<!-- <el-button @click="cancel()" :loading="submitLoading">返回</el-button> -->
						<el-button type="primary" @click="submitForm()" :loading="submitLoading">保存</el-button>
					</div>
				</el-row>
			</el-col>
			<el-col :span="12">
				<el-row>
					<el-col :span="24">
						<div class="address-box">
							<div class="address-content">
								<AddressItem
									:item="addressItem"
									:defaultItem="defaultAddressItem"
									:dialogVisible="dialogVisible"
									:loading="addressLoading"
									@submit="(item) => editAddressItem(item)"
									@closeDialog="onColseDialog(bl)"
								/>
							</div>
							<div class="address-header">
								<el-button type="primary" @click="setIsShowDrawer(true)">管理地址</el-button>
							</div>
						</div>
					</el-col>
					<el-col :span="24">
						<h2 style="padding: 25px 0 18px">社媒地址</h2>
						<el-form :model="detailItem" label-width="100px">
							<el-form-item label="faceBook">
								<el-input show-word-limit maxlength="200" v-model="detailItem.faceBook" placeholder="请输入电话号码" style="width: 100%" />
							</el-form-item>
							<el-form-item label="twitter">
								<el-input show-word-limit maxlength="200" v-model="detailItem.twitter" placeholder="请输入电话号码" style="width: 100%" />
							</el-form-item>
							<el-form-item label="INS">
								<el-input show-word-limit maxlength="200" v-model="detailItem.ins" placeholder="请输入电话号码" style="width: 100%" />
							</el-form-item>
							<el-form-item label="pinterest">
								<el-input show-word-limit maxlength="200" v-model="detailItem.pinterest" placeholder="请输入电话号码" style="width: 100%" />
							</el-form-item>
						</el-form>
					</el-col>
				</el-row>
			</el-col>
		</el-row>
		<div class="manage-h2">订单信息</div>
		<el-row :gutter="20">
			<el-col :span="24">
				<el-table v-loading="tableLoading" :data="tableData" style="width: 100%">
					<el-table-column prop="orderNumber" label="序号" show-overflow-tooltip></el-table-column>
					<el-table-column width="250px" label="订单编号" show-overflow-tooltip>
						<template #default="scope">
							<el-link type="primary" @click="$router.push({ path: '/order', query: { id: scope.row.id } })">{{ scope.row.orderSn }}</el-link>
						</template>
					</el-table-column>
					<el-table-column prop="totalAmount" label="订单金额" show-overflow-tooltip></el-table-column>
					<el-table-column
						label="商品数量"
						:formatter="
							(row, column, cellValue, index) => {
								return (row.orderItemDetail ? row.orderItemDetail.length : 0) + `件`;
							}
						"
						show-overflow-tooltip
					></el-table-column>
					<el-table-column prop="status" label="订单状态" show-overflow-tooltip></el-table-column>
					<el-table-column prop="createTime" width="200px" label="时间" show-overflow-tooltip></el-table-column>
					<el-table-column prop="growth" label="送达国家" show-overflow-tooltip></el-table-column>
					<el-table-column prop="note" label="备注" show-overflow-tooltip></el-table-column>
				</el-table>
			</el-col>
		</el-row>

		<el-drawer :size="500" v-model="isShowDrawer" :lock-scroll="true" title="管理地址" direction="rtl" modal-class="manage-el-drawer">
			<AddressList :list="addressList" :customerId="customerId" @reload="getAddressList()" />
		</el-drawer>
	</div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import AddressItem from '/@/components/address/addressItem.vue';
import AddressList from '/@/components/address/addressList.vue';
import { useCustomerApi } from '/@/api/customer';
import { useTagsApi } from '/@/api/common/tags';
import { useOrderApi } from '/@/api/order';
import { ENABLE_TAG } from '/@/stores/tags';
import { timeFormat } from '/@/utils/filters';
import { deepCopy } from '/@/utils';
import commonFunction from '/@/utils/commonFunction';
import orderState from '/@/utils/pageState/orderState';

const { getCurrencySymbolTextBySite, getSiteByPlatform, getCountryText, getPayTypeText, getStatusText, getCityNameByShorthand } = commonFunction();
const { REFUND_OCCURRED } = orderState();
const { getCustomerDetail, updateCustomer, getCustomerAddressList, UpdateCustomerAddress } = useCustomerApi();
const { getTagsList } = useTagsApi();
const { getOrderList } = useOrderApi();

let loading = ref(false);
let dialogVisible = ref(false);
let submitLoading = ref(false);
let labelLoading = ref(false);
let tableLoading = ref(false);
let isReady = ref(false);
let detailItem = ref({
	id: '',
	icon: '',
	name: '',
	surname: '',
	email: '',
	username: '',
	businessname: '',
	allname: '',
	ssn: '',
	birthday: '',
	phoneNumber: '',
	faceBook: '',
	twitter: '',
	ins: '',
	pinterest: '',
	registrationTime: '',
	isSubscribe: '',
	label: [],
});
const props = defineProps({
	customerId: {
		type: Number,
		default: -1,
	},
});

const labelList = ref([]);
const phoneList = ref([]);
const ruleFormRef = ref(null);
let tableData = ref([]);
let isShowDrawer = ref(false);
// 地址
// 全部地址
let addressList = ref([]);
addressList.value = [];
// 默认展示的单个
let addressItem = ref({
	id: '',
});
let defaultAddressItem = ref({
	id: '',
});
let addressLoading = ref(false);
let rules = {
	name: [
		{
			required: true,
			message: '请输入名字',
			trigger: 'blur',
		},
	],
};

async function getDetail() {
	loading.value = true;
	try {
		let params = {
			id: props.customerId,
		};
		let res = await getCustomerDetail(params.id);
		if (res.code !== 200) {
			loading.value = false;
			return;
		}
		let item = res.data;

		let label = [];
		if (item.tag !== null && item.tag != '') {
			let tempTags = item.tag.split(',');
			for (let index = 0; index < tempTags.length; index++) {
				const element = tempTags[index];
				label.push(Number(element));
			}
		}
		detailItem.value = {
			id: item.id,
			icon: item.icon,
			name: item.firstname,
			surname: item.lastname,
			email: item.email,
			username: item.username,
			allname: item.firstname + ' ' + item.lastname,
			birthday: item.birthday,
			phoneNumber: item.phone,
			faceBook: item.faceBook,
			ins: item.ins,
			twitter: item.twitter,
			pinterest: item.pinterest,
			isSubscribe: item.isSubscribe === 1 ? '已订阅' : '未订阅',
			registrationTime: timeFormat(item.createTime),
			label,
		};
		phoneList.value = JSON.parse(item.phone) || [];
		loading.value = false;
		isReady.value = true;
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '获取详情失败',
		});
	}
}

async function getAddressList() {
	addressLoading.value = true;

	try {
		let params = {
			id: props.customerId,
		};
		let res = await getCustomerAddressList(params.id);
		if (res.code !== 200) {
			addressLoading.value = false;
			return;
		}
		let tempAddressList = [];
		tempAddressList = res.data.map((item) => {
			let tempItem = {
				id: item.id,
				isDefault: item.defaultStatus === 1 ? true : false,
				label: item.mark,
				firstName: item.firstName,
				lastName: item.lastName,
				address: item.detailAddress,
				city: item.city,
				countryValue: item.country,
				countryLabel: getCityNameByShorthand(item.country),
				postCode: item.postCode,
				phone: item.phoneNumber,
			};
			return {
				addressItem: tempItem,
				defaultAddressItem: JSON.parse(JSON.stringify(tempItem)),
				addressLoading: false,
			};
		});

		addressList.value = tempAddressList;

		let defalutAddress = tempAddressList.filter((item) => {
			if (item.addressItem.isDefault) {
				return item;
			}
		});
		if (defalutAddress.length > 0) {
			addressItem.value = defalutAddress[0].addressItem;
		}
		defaultAddressItem.value = deepCopy(addressItem.value);
		addressLoading.value = false;
	} catch (error) {
		addressLoading.value = false;
		ElMessage({
			type: 'error',
			message: '获取默认地址失败',
		});
	}
}

async function getLabelList() {
	labelLoading.value = true;
	try {
		let res = await getTagsList(ENABLE_TAG);
		if (res.code !== 200) {
			labelLoading.value = false;
			return;
		}
		labelLoading.value = false;

		let tempList = [];

		tempList = res.data.map((item) => {
			return {
				label: item.tagName,
				value: item.id,
			};
		});

		labelList.value = tempList;
	} catch (error) {
		labelLoading.value = false;
		ElMessage({
			type: 'error',
			message: '获取标签列表失败',
		});
	}
}

// 获取订单列表
async function getOrderListByManage() {
	tableLoading.value = true;
	let params = {
		current: 1,
		pageSize: 99999999,
		customerId: props.customerId,
	};
	let res = await getOrderList(params);
	if (res.code !== 200) {
		tableLoading.value = false;
		return;
	}

	try {
		let tempList = [];
		tempList = res.data.data.map((item, index) => {
			return {
				id: item.id,
				checked: false,
				orderNumber: (res.data.current - 1) * 10 + index + 1,
				orderSn: item.orderSn,
				createTime: timeFormat(item.createTime),
				memberUsername: item.receiverName,
				totalAmount: getCurrencySymbolTextBySite(item.sourceType) + item.payAmount,
				site: getSiteByPlatform(item.sourceType),
				couponAmount: item.couponAmount,
				growth: getCountryText(item.growth),
				isPayed: item.isPayed,
				payType: getPayTypeText(item.payType),
				status: item.isReturn === REFUND_OCCURRED ? '发生退款' : getStatusText(item.status),
				orderSource: item.sourceType,
				orderItemDetail: item.orderItemList,
				isReturn: item.isReturn,
				note: item.note ? item.note : '',
				isAfterSale: false,
			};
		});
		tableData.value = tempList;
		tableLoading.value = false;
		isReady.value = true;
	} catch (error) {
		tableLoading.value = false;
		ElMessage({
			type: 'error',
			message: '获取订单列表失败',
		});
	}
}

function setIsShowDrawer(state) {
	isShowDrawer.value = state;
}

function submitForm() {
	ruleFormRef.value.validate((valid) => {
		if (valid) {
			// alert('submit!')
			submit();
		} else {
			// console.log("error submit!!")
			return false;
		}
	});
}

async function submit() {
	submitLoading.value = true;
	try {
		let params = {};
		let res = null;
		// 修改
		let item = detailItem.value;
		// icon: 'https://st-future.oss-cn-hongkong.aliyuncs.com/img/1661147971569_cff5d8ea-77c8-456d-b672-34f2071b64da.jpg',
		params = {
			id: props.customerId,
			firstname: item.name,
			lastname: item.surname,
			email: item.email,
			businessname: item.businessname,
			ssn: item.ssn,
			faceBook: item.faceBook,
			twitter: item.twitter,
			ins: item.ins,
			pinterest: item.pinterest,
			phone: JSON.stringify(phoneList.value),
			tag: item.label.join(','),
		};
		console.log('0-0-0--', params);
		res = await updateCustomer(params);

		if (res.code !== 200) {
			submitLoading.value = false;
			return;
		}
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		submitLoading.value = false;
	} catch (error) {
		submitLoading.value = false;
		ElMessage({
			type: 'error',
			message: '保存失败',
		});
	}
}

const onColseDialog = (bl) => {
	dialogVisible.value = bl;
};

async function editAddressItem(item) {
	addressLoading.value = true;
	setTimeout(() => {
		addressLoading.value = false;
	}, 1000);

	try {
		let params = {};
		let res = null;
		// 修改
		params = {
			id: item.id,
			memberId: props.customerId,
			defaultStatus: item.isDefault ? 1 : 0,
			mark: item.label,
			firstName: item.firstName,
			lastName: item.lastName,
			detailAddress: item.address,
			city: item.city,
			country: item.countryValue,
			postCode: item.postCode,
			phoneNumber: item.phone,
		};
		res = await UpdateCustomerAddress(params);

		if (res.code !== 200) {
			addressLoading.value = false;
			return;
		}
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		addressLoading.value = false;
		getAddressList();
	} catch (error) {
		addressLoading.value = false;
		ElMessage({
			type: 'error',
			message: '保存失败',
		});
	}
}

function init() {
	if (props.customerId === 0) {
		return;
	}
	getDetail();
	getLabelList();
	getAddressList();
	getOrderListByManage();
}
onMounted(() => {
	init();
});
</script>
<style lang="scss" scoped>
.manage-detail {
	max-width: 1200px;
	margin: 0 auto;
	.manage-h1 {
		font-size: 30px;
	}
	.manage-h2 {
		font-size: 24px;
		margin-top: 30px;
		margin-bottom: 20px;
	}
	.manage-pic {
		width: 60px;
		height: 60px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #000000;
		color: white;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 auto;
		span {
			font-size: 30px;
		}
	}
	.address-box {
		position: relative;
		display: flex;
		flex-direction: column;
		max-width: 500px;
		.address-header {
			position: absolute;
			bottom: 10px;
			right: 0;
			.address-header-span {
				font-size: 20px;
			}
		}
		.address-content {
			padding: 10px;
		}
	}
	.line-box {
		display: flex;
		align-items: center;
		.input-name {
			width: 80px;
			text-align: right;
			padding-right: 15px;
		}
		.input-box {
			display: flex;
			flex: 1;
			overflow: hidden;
			align-items: center;
			.input-box-p {
				padding: 0 15px;
			}
			&.input-box-btns {
				width: 100%;
				justify-content: space-between;
			}
		}
	}
	.el-row {
		margin-bottom: 20px;
		&:last-child {
			margin-bottom: 0;
		}
	}

	.manage-btns {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
	}
}
</style>
<style lang="scss">
.manage-el-drawer {
	.el-drawer__body {
		height: 100px;
		overflow-y: auto;
	}
}
</style>
